﻿// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
using System;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.ApplicationPages;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using System.Web;
namespace Microsoft.MCSUK.SPSiteDirectory2010
{
    public class SiteDirectorySiteManager : LayoutsPageBase
    {
        protected System.Web.UI.WebControls.Literal ErrorMessageLiteral;
        protected Microsoft.SharePoint.WebControls.WebApplicationSelector WebAppSelector;
        protected System.Web.UI.WebControls.Button OKButton;
        protected System.Web.UI.WebControls.Label SiteDirectoryWebAppLabel;
        protected System.Web.UI.WebControls.DropDownList SiteDirectorySite;
        protected System.Web.UI.WebControls.Label SiteDirectoryStatusLabel;
        protected System.Web.UI.WebControls.Button DisableButton;
        protected override void OnLoad(EventArgs e)
        {
            GlobalMethods globalMethods = new GlobalMethods();
            if (!IsPostBack) ///we do not want to do anything on postbacks
            {
                GlobalSolutionSettings globalSettings = globalMethods.GetOrCreateGlobalSolutionSettings(SPFarm.Local);
                try
                {
                    if (globalMethods.DoesSiteExist(globalSettings.SiteDirectoryURL))
                    {
                        using (SPSite siteDirectorySite = new SPSite(globalSettings.SiteDirectorySiteGuid))
                        {
                            using (SPWeb siteDirectoryWeb = siteDirectorySite.OpenWeb(globalSettings.SiteDirectoryWebGuid))
                            {
                                SiteDirectoryStatusLabel.Text = string.Concat(HttpContext.GetGlobalResourceObject("SPSiteDirectory2010GlobalResources", "ADMIN_SiteDirectoryManager_StatusSection_SiteDirectoryActivated").ToString(), "<A href='", siteDirectoryWeb.Url.ToString(), "'>", siteDirectoryWeb.Url.ToString(), "</A>");
                            }
                        }
                    }
                    else
                    {
                        globalMethods.ResetGlobalSolutionSettings(SPFarm.Local);
                        SiteDirectoryStatusLabel.Text = HttpContext.GetGlobalResourceObject("SPSiteDirectory2010GlobalResources", "ADMIN_SiteDirectoryManager_StatusSection_SiteDirectoryNotActivated").ToString();
                    }
                }
                catch (Exception ex)
                {
                    globalMethods.ResetGlobalSolutionSettings(SPFarm.Local); //if there is a problem we just reset the settings
                    ErrorMessageLiteral.Text = HttpContext.GetGlobalResourceObject("SPSiteDirectory2010GlobalResources", "Code_GenericUIErrorText").ToString();
                    globalMethods.WriteULSEntry(ex, TraceSeverity.Unexpected, null);
                }
            }
        }
        protected void WebAppSelector_OnContextChange(object sender, EventArgs e)
        {
            GlobalMethods globalMethods = new GlobalMethods();
            try
            {
                if (WebAppSelector.CurrentItem != null)
                {
                    GlobalSolutionSettings globalSettings = globalMethods.GetOrCreateGlobalSolutionSettings(SPFarm.Local);
                    SiteDirectoryWebAppLabel.Text = WebAppSelector.CurrentItem.GetResponseUri(SPUrlZone.Default).ToString().TrimEnd('/'); //show the selected web application
                    SiteDirectorySite.Items.Clear();
                    foreach (SPSite site in this.WebAppSelector.CurrentItem.Sites) //populate the drop down list with all webs in web application
                    {
                        try
                        {
                            foreach (SPWeb web in site.AllWebs)
                            {
                                ListItem li = new ListItem(web.ServerRelativeUrl, (site.ID.ToString() + web.ID.ToString()));
                                SiteDirectorySite.Items.Add(li);   
                            }
                            site.Dispose();
                        }
                        finally
                        {
                            if (site != null)
                                site.Dispose();
                        }
                    }
                    if (globalMethods.DoesSiteExist(globalSettings.SiteDirectoryURL))
                    {
                        if (SiteDirectorySite.Items.FindByValue(globalSettings.SiteDirectoryWebGuid.ToString()) != null)
                        {
                            SiteDirectorySite.ClearSelection();
                            SiteDirectorySite.Items.FindByValue(globalSettings.SiteDirectoryWebGuid.ToString()).Selected = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMessageLiteral.Text = HttpContext.GetGlobalResourceObject("SPSiteDirectory2010GlobalResources", "Code_GenericUIErrorText").ToString();
                globalMethods.WriteULSEntry(ex, TraceSeverity.Unexpected, null);
            }
        }      
        protected void DisableButton_OnClick(object sender, EventArgs e)
        {
            GlobalMethods globalMethods = new GlobalMethods();
            try
            {
                GlobalSolutionSettings globalSettings = globalMethods.GetOrCreateGlobalSolutionSettings(SPFarm.Local);
                if (globalMethods.DoesSiteExist(globalSettings.SiteDirectoryURL))
                {
                    using (SPSite siteDirectorySite = new SPSite(globalSettings.SiteDirectorySiteGuid))
                    {
                        using (SPWeb siteDirectoryWeb = siteDirectorySite.OpenWeb(globalSettings.SiteDirectoryWebGuid))
                        {
                            siteDirectoryWeb.AllowUnsafeUpdates = true;
                            siteDirectoryWeb.Features.Remove(GlobalConstants.SiteListingsFeatureID, true);
                        }
                    }
                }
                globalMethods.ResetGlobalSolutionSettings(SPFarm.Local);
                SPUtility.Redirect(GlobalConstants.CentralAdminRedirectURL, SPRedirectFlags.Trusted | SPRedirectFlags.DoNotEndResponse, this.Context);
            }
            catch (Exception ex)
            {
                ErrorMessageLiteral.Text = HttpContext.GetGlobalResourceObject("SPSiteDirectory2010GlobalResources", "Code_GenericUIErrorText").ToString();
                globalMethods.WriteULSEntry(ex, TraceSeverity.Unexpected, null);
                globalMethods.ResetGlobalSolutionSettings(SPFarm.Local);
            }
        }
        protected void OKButton_OnClick(object sender, EventArgs e)
        {
            GlobalMethods globalMethods = new GlobalMethods();
            try
            {
                if (Page.IsValid)
                {
                    if (WebAppSelector.CurrentItem != null)
                    {
                        Guid selectedSiteGuid = new Guid(SiteDirectorySite.SelectedItem.Value.Substring(0, 36));
                        Guid selectedWebGuid = new Guid(SiteDirectorySite.SelectedItem.Value.Substring(36, 36));

                        GlobalSolutionSettings globalSettings = globalMethods.GetOrCreateGlobalSolutionSettings(SPFarm.Local);
                        using (SPSite selectedSite = new SPSite(selectedSiteGuid))
                        {
                            using (SPWeb selectedWeb = selectedSite.OpenWeb(selectedWebGuid))
                            {
                                selectedWeb.Features.Add(GlobalConstants.SiteListingsFeatureID, true);
                                globalSettings.SiteDirectorySiteGuid = selectedSite.ID;
                                globalSettings.SiteDirectoryWebGuid = selectedWeb.ID;
                                globalSettings.SiteDirectoryURL = selectedWeb.Url;
                                globalSettings.Update();
                            }
                        }
                    }
                    SPUtility.Redirect(GlobalConstants.CentralAdminRedirectURL, SPRedirectFlags.Trusted | SPRedirectFlags.DoNotEndResponse, this.Context);
                }
                else
                { 
                    ErrorMessageLiteral.Text = HttpContext.GetGlobalResourceObject("SPSiteDirectory2010GlobalResources", "ADMIN_Generic_InvalidPageControls").ToString();
                }
            }
            catch (Exception ex)
            {
                ErrorMessageLiteral.Text = HttpContext.GetGlobalResourceObject("SPSiteDirectory2010GlobalResources", "Code_GenericUIErrorText").ToString();
                globalMethods.WriteULSEntry(ex, TraceSeverity.Unexpected, null);
            }
        }
    }
}
